package com.clgk.wechatmall.partner.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.clgk.wechatmall.common.ThreadLocals;
import com.clgk.wechatmall.common.sql.CommonDaoImpl;
import com.clgk.wechatmall.common.sql.Page;
import com.clgk.wechatmall.manager.entity.ManagerVo;
import com.clgk.wechatmall.partner.bean.PartnerBean;
import com.clgk.wechatmall.partner.dao.PartnerDao;

@Repository
public class PartnerDaoImpl extends CommonDaoImpl implements PartnerDao {

	@Override
	public Integer dels(String ids) {
		String sql = "DELETE FROM lampserver.`T_PARTNER` WHERE ID IN ("+ids+")";
		return this.update(sql,new Object[]{});
	}

	@Override
	public List<PartnerBean> queryList(PartnerBean par, Page page) {
		StringBuilder sql = new StringBuilder();
		List<Object> params = new ArrayList<Object>();
		sql.append(" SELECT t.*,tc.`NAME` cityname  ");
		sql.append(" FROM lampserver.`T_PARTNER` t ");
		sql.append(" LEFT JOIN lampserver.`T_CITY` tc ON t.`CITYID` = tc.`ID` ");
		sql.append(" WHERE 1=1 ");
		ManagerVo bu = ThreadLocals.getBackUser();
		if(bu != null && bu.getType() > 9){
			sql.append(" AND FIND_IN_SET(t.`ID`,lampserver.`getPartnerList`(?)) ");
			params.add(bu.getPartnerid());
		}
		if(par != null){
			if(par.getParentid() != null){
				sql.append(" AND t.`PARENTID`=? ");
				params.add(par.getParentid());
			}
			if(StringUtils.isNotBlank(par.getPartnername())){
				sql.append(" AND t.`PARTNERNAME` LIKE ? ");
				params.add("%" + par.getPartnername() + "%");
			}
			if(par.getType() != null){
				sql.append("  AND t.`TYPE`=? ");
				params.add(par.getType());
			}
			if(par.getId() != null){
				sql.append(" AND  t.`ID`=? ");
				params.add(par.getId());
			}
		}
		return super.query(sql.toString(), PartnerBean.class, params,page);
	}

	@Override
	public List<PartnerBean> queryTree() {
		String sql = "SELECT tp.* FROM lampserver.`T_PARTNER` tp ";
		ManagerVo bu = ThreadLocals.getBackUser();
		if(bu.getType() >= 10){
			sql += "WHERE FIND_IN_SET(tp.`ID`,lampserver.`getPartnerList`("+bu.getPartnerid()+"))";
		}
		return super.query(sql, PartnerBean.class, new Object[]{});
	}

}
